package com.note.simpleshop.module.cart.service;
import com.note.simpleshop.entity.TbCart;
import com.note.simpleshop.entity.TbGoods;
import com.note.simpleshop.entity.TbGoodsSpec;
import com.note.simpleshop.exception.NotDataException;
import com.note.simpleshop.module.cart.dao.CartRepository;
import com.note.simpleshop.module.cart.vo.CartVo;
import com.note.simpleshop.module.goods.service.GoodsService;
import com.note.simpleshop.module.goods.service.GoodsSpecService;
import com.note.simpleshop.module.goods.vo.GoodsSpecVo;
import com.note.simpleshop.module.goods.vo.GoodsVo;
import com.note.simpleshop.utils.DateUtil;
import com.note.simpleshop.utils.IdGenerator;
import com.note.simpleshop.vo.PageBean;
import javafx.event.Event;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Service
public class CartService {
    @Autowired
    private CartRepository cartRepository;
    @Autowired
    private GoodsSpecService goodsSpecService;
    @Autowired
    private GoodsService goodsService;

    /***
     *
     * 实时查询商品信息
     * @param userId
     * @param cartIds
     * @return
     */
    public List<CartVo> findByCardIds(String userId, List<String> cartIds)
    {
        List<CartVo> cartVoList=new ArrayList<CartVo>();
        List<TbCart> cartList=cartRepository.findByUserIdAndIdInAndIsDelete(userId,cartIds,TbCart.IS_DELEETE0);
        for(TbCart tbCart:cartList)
        {
            CartVo cartVo=CartVo.newInstance(tbCart);
            //查询商品规格信息
            TbGoodsSpec goodsSpec=goodsSpecService.findById(tbCart.getGoodsSpecId());
            GoodsSpecVo goodsSpecVo=GoodsSpecVo.newInstance(goodsSpec);
            cartVo.setGoodsSpec(goodsSpecVo);
            //查询商品基本信息
            TbGoods goods=goodsService.findCacheById(tbCart.getGoodsId());
            GoodsVo goodsVo=GoodsVo.copy(goods);
            cartVo.setGoods(goodsVo);
            cartVoList.add(cartVo);
        }
        return cartVoList;
    }

    /***
     *
     * 查询商品信息走缓存
     * @param userId
     * @param cartIds
     * @return
     */
    public List<CartVo> findCacheByCardIds(String userId,List<String> cartIds)
    {
        List<CartVo> cartVoList=new ArrayList<CartVo>();
        List<TbCart> cartList=cartRepository.findByUserIdAndIdInAndIsDelete(userId,cartIds,TbCart.IS_DELEETE0);
        for(TbCart tbCart:cartList)
        {
            CartVo cartVo=CartVo.newInstance(tbCart);
            //查询商品规格信息
            TbGoodsSpec goodsSpec=goodsSpecService.findCacheById(tbCart.getGoodsSpecId());
            GoodsSpecVo goodsSpecVo= GoodsSpecVo.newInstance(goodsSpec);
            cartVo.setGoodsSpec(goodsSpecVo);
            //查询商品基本信息
            TbGoods goods=goodsService.findCacheById(tbCart.getGoodsId());
            GoodsVo goodsVo= GoodsVo.copy(goods);
            cartVo.setGoods(goodsVo);
            cartVoList.add(cartVo);
        }
        return cartVoList;
    }
    public PageBean findByPage(Integer pageNumber, String userId) {
        if (pageNumber == null) {
            pageNumber = 0;
        }
        else
        {
            pageNumber=pageNumber-1;
        }
        Sort sort = new Sort(Sort.Direction.DESC, "addTime");
        PageRequest pageRequest = new PageRequest(pageNumber, 20, sort);
        Specification<TbCart> specification=new Specification<TbCart>() {
            private static final long serialVersionUID = 1L;
            @Override
            public Predicate toPredicate(Root<TbCart> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(criteriaBuilder.equal(root.get("isDelete"), TbCart.IS_DELEETE0));
                predicates.add(criteriaBuilder.equal(root.get("userId"), userId));
                return  criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Page<TbCart> page = cartRepository.findAll(specification,pageRequest); //根据这个分页对象获取分页对象
        //获取购物车中商品的信息
        List<TbCart> list=page.getContent();
        List<CartVo> cartVoList=new ArrayList<CartVo>();
        for(TbCart tbCart:list)
        {
            CartVo cartVo=CartVo.newInstance(tbCart);
            //查询商品规格信息
            TbGoodsSpec goodsSpec=goodsSpecService.findCacheById(tbCart.getGoodsSpecId());
            GoodsSpecVo goodsSpecVo=GoodsSpecVo.newInstance(goodsSpec);
            cartVo.setGoodsSpec(goodsSpecVo);
            //查询商品基本信息
            TbGoods goods=goodsService.findCacheById(tbCart.getGoodsId());
            GoodsVo goodsVo=GoodsVo.copy(goods);
            cartVo.setGoods(goodsVo);
            cartVoList.add(cartVo);
        }
        PageBean<CartVo> pageBean=new PageBean(page.getTotalPages(),(int)page.getTotalElements(),page.isFirst(),page.isEmpty(),page.getNumber(), cartVoList);;
        return pageBean;
    }
    public void updateCart(String userId,String cartId,Integer num) throws NotDataException
    {
        //用户权限验证
        TbCart cart=cartRepository.findByIdAndUserIdAndIsDelete(cartId,userId,TbCart.IS_DELEETE0);
        if(cart==null)
        {
            throw new NotDataException("购物车信息不存在");
        }
        cartRepository.updateCart(num,cartId);
    }
    public void deleteCart(String userId,String cartId) throws NotDataException {
        //用户权限验证
        TbCart cart = cartRepository.findByIdAndUserIdAndIsDelete(cartId, userId, TbCart.IS_DELEETE0);
        if (cart == null) {
            throw new NotDataException("购物车信息不存在");
        } else
        {
            cartRepository.deleteCart(TbCart.IS_DELETE1,cartId);
        }
    }
    public void addCart(TbCart model) throws NotDataException
    {
        String goodsSpecId=model.getGoodsSpecId();
        //判断商品是否存在
       TbGoodsSpec goodsSpec= goodsSpecService.findById(goodsSpecId);
       if(goodsSpec==null)
       {
           throw new NotDataException("商品不存在");
       }
        String currentUserId=model.getUserId();
        TbCart cart=cartRepository.findByIsDeleteAndGoodsSpecIdAndUserId(TbCart.IS_DELEETE0,goodsSpecId,currentUserId);
        if(cart!=null)
        {
            cartRepository.updateCart(model.getNum()+cart.getNum(),cart.getId());
        }
        else
        {
            model.setIsDelete(TbCart.IS_DELEETE0);
            model.setAddTime(DateUtil.getTimestamp());
            model.setId(IdGenerator.id());
            cartRepository.save(model);
        }
    }
}
